import express from 'express';
import doctorRoutes from './doctors.js';
import scoringRoutes from './scoring.js';
import authRoutes from './auth.js';
import databaseRoutes from './database.js';
import monitoringRoutes from './monitoring.js';
import phase2Routes from './phase2Simple.js';
import axios from 'axios';

const router = express.Router();

// API路由前缀
router.use('/auth', authRoutes);
router.use('/doctors', doctorRoutes);
router.use('/scoring', scoringRoutes);
router.use('/database', databaseRoutes);
router.use('/monitoring', monitoringRoutes);
router.use('/phase2', phase2Routes);

// API健康检查
router.get('/health', (req, res) => {
  res.json({
    success: true,
    message: 'EndoSight-UC API 运行正常',
    data: {
      timestamp: new Date().toISOString(),
      version: '1.0.0',
      environment: process.env.NODE_ENV || 'development'
    }
  });
});

// AI健康检查代理
router.get('/ai/health', async (req, res) => {
  try {
    // 从AI_INFERENCE_URL中提取基础URL
    const aiBaseUrl = process.env.AI_INFERENCE_URL || 'http://localhost:5001';
    const healthUrl = aiBaseUrl.replace('/v1/predict', '') + '/health';

    const response = await axios.get(healthUrl, {
      timeout: 5000,
      headers: {
        'Accept': 'application/json'
      }
    });

    res.json(response.data);
  } catch (error) {
    console.error('AI健康检查失败:', error.message);
    res.status(500).json({
      success: false,
      message: 'AI服务连接失败',
      data: null
    });
  }
});

// 系统状态端点 (修复前端404错误)
router.get('/system/status', (req, res) => {
  const now = new Date();
  const uptime = process.uptime();

  res.json({
    success: true,
    message: '系统状态正常',
    data: {
      status: 'healthy',
      timestamp: now.toISOString(),
      uptime: {
        seconds: Math.floor(uptime),
        human: `${Math.floor(uptime / 3600)}h ${Math.floor((uptime % 3600) / 60)}m ${Math.floor(uptime % 60)}s`
      },
      services: {
        api: 'running',
        database: 'connected',
        ai: 'connected'
      },
      version: '1.0.0',
      environment: process.env.NODE_ENV || 'development',
      memory: {
        used: Math.round(process.memoryUsage().heapUsed / 1024 / 1024) + 'MB',
        total: Math.round(process.memoryUsage().heapTotal / 1024 / 1024) + 'MB'
      }
    }
  });
});

export default router;